package com.ruoyi.veterinary.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.veterinary.mapper.VetOutboundMapper;
import com.ruoyi.veterinary.domain.VetOutbound;
import com.ruoyi.veterinary.domain.VetInventory;
import com.ruoyi.veterinary.service.IVetOutboundService;
import com.ruoyi.veterinary.service.IVetInventoryService;
import com.ruoyi.common.exception.ServiceException;

/**
 * 出货管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-19
 */
@Service
public class VetOutboundServiceImpl implements IVetOutboundService 
{
    @Autowired
    private VetOutboundMapper vetOutboundMapper;
    
    @Autowired
    private IVetInventoryService vetInventoryService;

    /**
     * 查询出货管理
     * 
     * @param outboundId 出货管理主键
     * @return 出货管理
     */
    @Override
    public VetOutbound selectVetOutboundByOutboundId(Long outboundId)
    {
        return vetOutboundMapper.selectVetOutboundByOutboundId(outboundId);
    }

    /**
     * 查询出货管理列表
     * 
     * @param vetOutbound 出货管理
     * @return 出货管理
     */
    @Override
    public List<VetOutbound> selectVetOutboundList(VetOutbound vetOutbound)
    {
        return vetOutboundMapper.selectVetOutboundList(vetOutbound);
    }

    /**
    /**
     * 新增出货管理
     * 
     * @param vetOutbound 出货管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertVetOutbound(VetOutbound vetOutbound)
    {
        // 1. 检查库存是否充足
        VetInventory inventory = vetInventoryService.selectInventoryByDrugAndBatch(
            vetOutbound.getDrugName(), vetOutbound.getBatchNumber());
        
        if (inventory == null) {
            throw new ServiceException("未找到对应的库存信息：" + vetOutbound.getDrugName() + " 批号：" + vetOutbound.getBatchNumber());
        }
        
        if (inventory.getQuantity() < vetOutbound.getQuantity()) {
            throw new ServiceException("库存不足！当前库存：" + inventory.getQuantity() + "，出货数量：" + vetOutbound.getQuantity());
        }
        
        // 2. 如果没有提供出货单号，自动生成
        if (vetOutbound.getOutboundOrderNo() == null || vetOutbound.getOutboundOrderNo().isEmpty()) {
            String orderNo = generateOutboundOrderNo();
            vetOutbound.setOutboundOrderNo(orderNo);
        }
        
        // 3. 计算总金额
        if (vetOutbound.getUnitPrice() != null && vetOutbound.getQuantity() != null) {
            vetOutbound.setTotalAmount(vetOutbound.getUnitPrice().multiply(
                java.math.BigDecimal.valueOf(vetOutbound.getQuantity())));
        }
        
        vetOutbound.setCreateTime(DateUtils.getNowDate());
        
        // 4. 保存出货记录
        int result = vetOutboundMapper.insertVetOutbound(vetOutbound);
        
        // 5. 扣减库存
        if (result > 0) {
            vetInventoryService.updateInventoryQuantity(inventory.getInventoryId(), -vetOutbound.getQuantity());
        }
        
        return result;
    }

    /**
     * 修改出货管理
     * 
     * @param vetOutbound 出货管理
     * @return 结果
     */
    @Override
    public int updateVetOutbound(VetOutbound vetOutbound)
    {
        vetOutbound.setUpdateTime(DateUtils.getNowDate());
        return vetOutboundMapper.updateVetOutbound(vetOutbound);
    }

    /**
     * 批量删除出货管理
     * 
     * @param outboundIds 需要删除的出货管理主键
     * @return 结果
     */
    @Override
    public int deleteVetOutboundByOutboundIds(Long[] outboundIds)
    {
        return vetOutboundMapper.deleteVetOutboundByOutboundIds(outboundIds);
    }

    /**
     * 删除出货管理信息
     * 
     * @param outboundId 出货管理主键
     * @return 结果
     */
    @Override
    public int deleteVetOutboundByOutboundId(Long outboundId)
    {
        return vetOutboundMapper.deleteVetOutboundByOutboundId(outboundId);
    }

    /**
     * 生成出货单号
     * 
     * @return 出货单号
     */
    @Override
    public String generateOutboundOrderNo()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        // 这里可以根据实际需求实现序号生成逻辑
        String sequence = String.format("%03d", (int)(Math.random() * 1000));
        return "CH" + dateStr + sequence;
    }

    /**
     * 出库操作（包含库存扣减）
     * 
     * @param vetOutbound 出货信息
     * @return 结果
     */
    @Override
    @Transactional
    public int processOutbound(VetOutbound vetOutbound)
    {
        // 1. 检查库存是否充足
        VetInventory inventory = vetInventoryService.selectInventoryByDrugAndBatch(
            vetOutbound.getDrugName(), vetOutbound.getBatchNumber());
        
        if (inventory == null) {
            throw new ServiceException("未找到对应的库存信息");
        }
        
        if (inventory.getQuantity() < vetOutbound.getQuantity()) {
            throw new ServiceException("库存不足，当前库存：" + inventory.getQuantity());
        }
        
        // 2. 生成出货单号
        if (vetOutbound.getOutboundOrderNo() == null || vetOutbound.getOutboundOrderNo().isEmpty()) {
            vetOutbound.setOutboundOrderNo(generateOutboundOrderNo());
        }
        
        // 3. 设置关联库存ID和休药期
        // 3. 计算总金额
        vetOutbound.setTotalAmount(vetOutbound.getUnitPrice().multiply(
            java.math.BigDecimal.valueOf(vetOutbound.getQuantity())));
        
        // 4. 保存出货记录
        int result = insertVetOutbound(vetOutbound);
        
        // 5. 扣减库存
        if (result > 0) {
            vetInventoryService.updateInventoryQuantity(inventory.getInventoryId(), -vetOutbound.getQuantity());
        }
        
        return result;
    }
}